from django.shortcuts import render, get_object_or_404
from django.views.generic import ListView, DetailView

from operate.forms import CommentForm
from operate.models import Comment
from .models import *


# Create your views here.



class ArticleListView(ListView):
    # model = Article

    def get_queryset(self):
        c_id = self.request.GET.get('category')
        if c_id and c_id != "all":
            cat = get_object_or_404(Category, id=c_id)
            queryset = cat.article_set.all()
        else:
            queryset = Article.objects.all()
        return queryset

    paginate_by = 10


    def get_context_data(self, **kwargs):
        kwargs.update({
            'category': self.request.GET.get('category') or "all",
        })
        
        # 添加浏览量排行榜数据（统计每个文章的浏览次数，取前十名）
        # 使用annotate和count来统计每个文章的浏览次数，统计所有记录（包括已删除的）以保持浏览次数准确
        from django.db.models import Count
        top_viewed_articles = BrowseHistory.objects.values('article').annotate(
            view_count=Count('article')
        ).order_by('-view_count')[:10]
        
        # 获取完整的文章信息
        most_viewed_articles = []
        for item in top_viewed_articles:
            article = Article.objects.get(id=item['article'])
            most_viewed_articles.append({
                'article': article,
                'view_count': item['view_count']
            })
        
        kwargs['most_viewed_articles'] = most_viewed_articles
        
        return super().get_context_data(**kwargs)
        


class ArticleDetailView(DetailView):
    queryset = Article.objects.all()
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        # 获取当前文章对象
        article = self.object
        # 只获取当前文章的顶级评论（parent为空的评论）
        context['comments'] = Comment.objects.filter(article=article, parent__isnull=True)
        # 添加评论表单
        context['form'] = CommentForm()
        return context


from django.contrib.auth.decorators import login_required
from django.utils import timezone

@login_required
def history_view(request):
    """
    浏览历史视图函数
    只显示用户真实的浏览历史记录（未删除的）
    """
    # 从数据库获取用户的未删除浏览历史记录
    history_records = BrowseHistory.objects.filter(user=request.user, is_deleted=False).order_by('-browse_time')
    
    # 转换真实记录为模板可用的格式
    history_data = []
    for record in history_records:
        history_data.append({
            'id': record.id,  # 添加记录ID，用于删除功能
            'article_title': record.article.title,
            'article_author': record.article.author.username,
            'article_id': record.article.id,
            'browse_time': record.browse_time
        })
    
    # 准备上下文数据
    context = {
        'test_data': history_data,  # 显示的数据
    }
    
    return render(request, 'main/history.html', context)

@login_required
def delete_history(request, history_id):
    """
    标记删除指定的浏览历史记录（软删除）
    """
    try:
        # 获取要删除的记录，确保是当前用户的记录
        history = BrowseHistory.objects.get(id=history_id, user=request.user)
        # 软删除：标记为已删除而不是真正删除
        history.is_deleted = True
        history.save()
        # 删除成功后重定向回历史记录页面
        from django.http import HttpResponseRedirect
        return HttpResponseRedirect('/article/history/')
    except BrowseHistory.DoesNotExist:
        # 如果记录不存在，返回404
        from django.http import Http404
        raise Http404("浏览历史记录不存在")

